package com.terabits.smartriver.service.impl;

import com.terabits.smartriver.mapper.RoleMapper;
import com.terabits.smartriver.mapper.UserMapper;
import com.terabits.smartriver.meta.po.User;
import com.terabits.smartriver.service.UserService;
import com.terabits.smartriver.util.PageData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * Created by Yin on 2019/2/11
 */
@Service
public class UserServiceImpl extends BaseService implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public User findUserByOpenid(String openid) {
        List<User> users = findObjectsByProperty("openid", openid, userMapper, User.class);

        if (users == null || users.size() != 1) {
            return null;
        }
        return users.get(0);
    }

    @Override
    public User findUserByPhone(String phone) {
        List<User> users = findObjectsByProperty("phone", phone, userMapper, User.class);

        if (users == null || users.size() != 1) {
            return null;
        }
        return users.get(0);
    }

    @Override
    public User findUserByUserName(String username) {
        List<User> users = findObjectsByProperty("username", username, userMapper, User.class);

        if (users == null || users.size() != 1) {
            return null;
        }
        return users.get(0);
    }

    @Override
    public List<User> getUser(PageData pageData) {

        String username = pageData.getString("username");
        if (username == null) {
            return userMapper.selectAll();
        }
        Example example = new Example(User.class);
        example.createCriteria().andLike("username", username);

        return userMapper.selectByExample(example);
    }

    @Override
    public int addUser(User user) {
        List users = findObjectsByProperty("username", user.getUsername(), userMapper, User.class);

        if (users != null && users.size() != 0) {
            return -1;
        }

        return userMapper.insertSelective(user);

    }

    @Override
    public int updateUser(User user) {
        if (!StringUtils.isEmpty(user.getStatus())) {
            Integer status = userMapper.selectByPrimaryKey(user.getId()).getStatus();
            status = (status == 1 ? 0 : 1);
            user.setStatus(status);
        }
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public int deleteUser(Integer userId) {
        roleMapper.deleteUserRoleByUserId(userId);
        return userMapper.deleteByPrimaryKey(userId);
    }
}
